import Access from '@/components/Access';
import {
  ActionType,
  ModalForm,
  ProColumns,
  ProFormDatePicker,
  ProFormDigit,
  ProFormInstance,
  ProFormRadio,
  ProFormText,
  ProFormTextArea,
  ProFormUploadButton,
  ProTable,
} from '@/components/Pro/';
// import { BATTERY_BOX_TYPE, DEVICE_TYPE } from '@/dictionary';
import Tabs, { TabsProps } from '@/components/Tabs';
import {
  deviceManagerControllerAdd as add,
  deviceManagerControllerBatchDelete as batchDelete,
  deviceManagerControllerBatchEnOrDisableDevices as batchDisabled,
  deviceManagerControllerDeviceList as getList,
  deviceManagerControllerEdit as edit,
  deviceManagerControllerUploadPic as uploadPic,
} from '@/services/ess/deviceManager';
import { getGlobalHandleTip } from '@/utils';
import { getIntl } from '@umijs/max';
import type { DatePickerProps, UploadFile, UploadProps } from 'antd';
import { Col, Image, message, Modal, Row, Space, Switch } from 'antd';
import moment from 'moment';
import { forwardRef, useImperativeHandle, useRef, useState } from 'react';
import { useAccess, useIntl, useModel } from 'umi';
import Styles from '../index.less';

const { confirm } = Modal;

/**
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.DeviceManagerReq) => {
  try {
    const res = await add({
      ...fields,
    });
    if (res.success) {
      getGlobalHandleTip('ADD');
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.addFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 编辑节点
 * @param fields
 */
const handleEdit = async (fields: API.DeviceBasicDocVO) => {
  try {
    const res = await edit({
      ...fields,
    });
    if (res.success) {
      getGlobalHandleTip('EDIT');
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.editFailedTips' }));
    return false;
  }
};

/**
 * @zh-CN 删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.DeviceBasicDocVO[]) => {
  if (!selectedRows) return true;
  try {
    const res = await batchDelete(selectedRows.map((row) => row.id));
    if (res.success) {
      getGlobalHandleTip('DEL');
      return true;
    }
    return false;
  } catch (error) {
    message.error(getIntl().formatMessage({ id: 'global.delFailedTips' }));
    return false;
  }
};

interface TableProps {
  deveiceType?: number;
  titleName?: string;
}

const Table = forwardRef((props: TableProps, ref: any) => {
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [activeTab, setActiveTab] = useState('1');
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<API.DeviceBasicDocVO>({});
  const [selectedRowsState, setSelectedRows] = useState<API.DeviceBasicDocVO[]>([]);
  const [readonly, setReadonly] = useState(false);
  const [deleteDisabled, setDeleteDisabled] = useState(false);
  const [imgUrl, setImgUrl] = useState(undefined);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const intl = useIntl();
  const { deveiceType, titleName } = props;
  const access = useAccess();

  const BATTERY_BOX_TYPE = {
    1: {
      text: intl.formatMessage({
        id: 'systemManagement.supplementary.airCooler',
      }),
    },
    2: {
      text: intl.formatMessage({
        id: 'systemManagement.supplementary.liquidCooler',
      }),
    },
  };

  const DEVICE_TYPE = {
    3: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.pcs',
      }),
      order: 1,
    },
    1: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.Batterycabinet',
      }),
      order: 2,
    },
    2: {
      text: intl.formatMessage({
        id: 'systemManagement.deviceManagementMenu.Batteryboxs',
      }),
      order: 3,
    },
  };

  const deleteRow = (rows: API.DeviceBasicDocVO[] = selectedRowsState) => {
    if (rows?.length < 1) {
      message.warning(intl.formatMessage({ id: 'global.leastOne' }));
      return;
    }

    if (deleteDisabled) return;
    setDeleteDisabled(true);

    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: intl.formatMessage({
        id: 'systemManagement.supplementary.dataCannotBeRestoredAfterDeletion',
      }),
      onOk: async () => {
        const res = await handleRemove(rows);
        if (res) {
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.();
        }
      },
      afterClose: () => {
        setDeleteDisabled(false);
      },
    });
  };

  const disabledDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    if (from) {
      return Math.abs(current.diff(from, 'years')) >= 3;
    }
  };

  useImperativeHandle(ref, () => ({
    add: () => {
      setImgUrl(undefined);
      setFileList([]);
      setReadonly(false);
      setCurrentRow({});
      handleModalOpen(true);
    },
    delete: () => {
      deleteRow();
    },
  }));

  const onRemove: UploadProps['onRemove'] = () => {
    setFileList([]);
    setImgUrl(undefined);
  };

  const handlePreview = async () => {
    setPreviewOpen(true);
  };

  const uploadImg: UploadProps = {
    name: 'file',
    listType: 'picture-card',
    fileList: fileList,
    onRemove: onRemove,
    onPreview: handlePreview,
    maxCount: 1,
    accept: 'image/png, image/jpeg, image/jpg',
    multiple: false,
    customRequest: async (info) => {
      console.log('info', info);
      const isLt5M = info.file?.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        message.error(intl.formatMessage({ id: 'systemManagement.neddTochange.imgMax' }));
        return;
      }
      const res = await uploadPic({
        attr: info.file,
      });
      if (res?.success) {
        const url = res?.data?.device;
        setImgUrl(url);
        setFileList([{ ...info.file, url, status: 'done' }]);
        message.success(
          `${info.file.name} ${intl.formatMessage({
            id: 'systemManagement.neddTochange.imageUploadSuccess',
          })}`,
        );
        return info.file;
      }
      const msg = info?.file?.response?.message;
      message.error(
        `${info.file.name} ${intl.formatMessage({
          id: 'systemManagement.neddTochange.imageUploadFailed',
        })}  ${msg ? ',' + msg : ''}`,
      );
    },
  };

  const handleColNum = access.calcPermsLen([
    'sys:device:edit',
    'sys:device:detail',
    'sys:device:del',
  ]);

  const columns: ProColumns<API.DeviceBasicDocVO>[] = [
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.SN' }),
      dataIndex: 'pageIndex',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.Factory' }),
      dataIndex: 'manufacturer',
      width: 100,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.DeviceType' }),
      dataIndex: 'deviceType',
      valueEnum: DEVICE_TYPE,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.Devicemodel' }),
      dataIndex: 'deviceModel',
      order: 1,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.status' }),
      dataIndex: 'status',
      valueEnum: {
        true: {
          text: intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' }),
        },
        false: {
          text: intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' }),
        },
      },
      hideInTable: !access.can('sys:device:setStatus'),
      render: (_, record) => (
        <Switch
          checkedChildren={intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' })}
          unCheckedChildren={intl.formatMessage({
            id: 'systemManagement.generalProcedure.disable',
          })}
          checked={Boolean(record.status)}
          onChange={(checked) => {
            confirm({
              title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
              content: checked
                ? intl.formatMessage({ id: 'systemManagement.neddTochange.confirmEnableSelected' })
                : intl.formatMessage({
                    id: 'systemManagement.neddTochange.confirmDisableSelected',
                  }),
              onOk: async () => {
                const res = await batchDisabled({
                  deviceIds: [record.id],
                  status: checked,
                });
                if (res?.success) {
                  getGlobalHandleTip('ENABLE');
                  actionRef.current?.reloadAndRest?.();
                }
              },
            });
          }}
        />
      ),
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.type' }),
      dataIndex: 'type',
      valueEnum: BATTERY_BOX_TYPE,
      hideInSearch: true,
      width: 90,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.RatedCapacity' }),
      dataIndex: 'ratedCap',
      render: (_, record) => record?.dcInfo?.ratedCap + 'kWh',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.stacksNumber' }),
      dataIndex: 'bmsNum',
      hideInSearch: true,
      width: 80,
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.supplementary.numberOfClustersInEachStack',
      }),
      dataIndex: 'clusterPerBms',
      hideInSearch: true,
      width: 110,
    },
    {
      title: intl.formatMessage({
        id: 'systemManagement.supplementary.numberOfModulesInEachCluster',
      }),
      dataIndex: 'bmuPerBms',
      hideInSearch: true,
      width: 130,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.supplementary.numberOfCellsInEachModule' }),
      dataIndex: 'cellPerBmu',
      hideInSearch: true,
      width: 130,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.RatedPower' }),
      dataIndex: 'ratedPower',
      render: (_, record) => record?.dcInfo?.ratedPower + 'kW',
      hideInSearch: true,
      width: 100,
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.listingTime' }),
      dataIndex: 'listingDay',
      width: 120,
      render: (_, record) => record.listingDay,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startListingDay: value[0],
            endListingDay: value[1],
          };
        },
      },
      initialValue: [moment().subtract(1, 'years'), moment()],
      fieldProps: {
        disabledDate: disabledDate,
        allowClear: false,
      },
    },
    {
      title: intl.formatMessage({ id: 'systemManagement.generalProcedure.operation' }),
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      hideInTable: handleColNum === 0,
      width: handleColNum * 60,
      render: (_, record) => (
        <Space>
          <Access perm="sys:device:edit" key="edit">
            <a
              key="edit"
              onClick={() => {
                setReadonly(false);
                handleModalOpen(true);
                const url = record.pictureDir;
                const file = {
                  uid: '-1',
                  name: url,
                  status: 'done',
                  url: url,
                };
                setImgUrl(url);
                setFileList([file]);
                setCurrentRow({
                  ...record,
                  pictureDir: {
                    file: file,
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })}
            </a>
          </Access>
          <Access perm="sys:device:detail" key="detail">
            <a
              key="detail"
              onClick={() => {
                setReadonly(true);
                handleModalOpen(true);
                const url = record.pictureDir;
                const file = {
                  uid: '-1',
                  name: url,
                  status: 'done',
                  url: url,
                };
                setImgUrl(url);
                setFileList([file]);
                setCurrentRow({
                  ...record,
                  pictureDir: {
                    file: file,
                  },
                });
              }}
            >
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.detail' })}
            </a>
          </Access>
          <Access perm="sys:device:del" key="del">
            <a key="delete" className="global-del-color" onClick={() => deleteRow([record])}>
              {intl.formatMessage({ id: 'systemManagement.generalProcedure.delete' })}
            </a>
          </Access>
        </Space>
      ),
    },
  ];

  const formItemLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };
  // Basic Info Form Component
  const BasicInfoForm = (
    <>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name="deviceModel"
            label={intl.formatMessage({ id: 'device.model' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.model' }) }]}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name="manufacturer"
            label={intl.formatMessage({ id: 'device.manufacturer' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzManufacturer' }) },
            ]}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormRadio.Group
            name="type"
            label={intl.formatMessage({ id: 'device.type' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzType' }) }]}
            options={[
              { label: intl.formatMessage({ id: 'baseInfo.air' }), value: '1' },
              { label: intl.formatMessage({ id: 'baseInfo.liquid' }), value: '2' },
            ]}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name="bmsNum"
            label={intl.formatMessage({ id: 'device.stackCount' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzStackCount' }) },
            ]}
            min={1}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name="clusterPerBms"
            label={intl.formatMessage({ id: 'device.clustersPerStack' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzClustersPerStack' }) },
            ]}
            min={1}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name="bmuPerBms"
            label={intl.formatMessage({ id: 'device.modulesPerCluster' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzModulesPerCluster' }),
              },
            ]}
            placeholder={intl.formatMessage({ id: 'strategyAction.pleaseEnter' })}
            min={1}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name="cellPerBmu"
            label={intl.formatMessage({ id: 'device.cellsPerModule' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzCellsPerModule' }) },
            ]}
            placeholder={intl.formatMessage({ id: 'strategyAction.pleaseEnter' })}
            min={1}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormRadio.Group
            name="status"
            label={intl.formatMessage({ id: 'device.status' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzStatus' }) }]}
            options={[
              {
                label: intl.formatMessage({ id: 'emsController.serial.status.enabled' }),
                value: true,
              },
              {
                label: intl.formatMessage({ id: 'emsController.serial.status.disabled' }),
                value: false,
              },
            ]}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDatePicker
            name="listingDay"
            label={intl.formatMessage({ id: 'device.marketLaunchDate' })}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormTextArea
            name="remark"
            label={intl.formatMessage({ id: 'device.remarks' })}
            fieldProps={{
              maxLength: 140,
              showCount: true,
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormUploadButton
            name="pictureDir"
            label={intl.formatMessage({ id: 'device.image' })}
            max={1}
            fieldProps={{
              ...uploadImg,
              accept: '.png,.jpg,.jpeg',
            }}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzImage' }) }]}
            title={intl.formatMessage({ id: 'device.image' })}
            description="支持PNG、JPEG类型"
            transform={(value) => {
              if (Array.isArray(value) && value[0]?.url) {
                return value[0].url;
              }
              return value;
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
    </>
  );

  // AC Parameters Form Component
  const ACParametersForm = (
    <>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['acInfo', 'ratedPower']}
            label={intl.formatMessage({ id: 'device.ratedPower' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzRatedPower' }) },
            ]}
            fieldProps={{
              addonAfter: 'kW',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name={['acInfo', 'ratedVol']}
            label={intl.formatMessage({ id: 'device.ratedVoltage' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzRatedVoltage' }) },
            ]}
            fieldProps={{
              addonAfter: 'V',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.acVoltageRange' })}
            {...formItemLayout}
          >
            <Space>
              <ProFormDigit name={['acInfo', 'volMin']} noStyle />
              <span>~</span>
              <ProFormDigit
                name={['acInfo', 'volMax']}
                noStyle
                fieldProps={{
                  addonAfter: 'V',
                }}
              />
            </Space>
          </ProFormText>
        </Col>
        <Col span={12}>
          <ProFormText
            name={['acInfo', 'wiringType']}
            label={intl.formatMessage({ id: 'device.wiringMethod' })}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.powerFactorRange' })}
            {...formItemLayout}
          >
            <Space>
              <ProFormDigit name={['acInfo', 'powerFactorMin']} noStyle />
              <span>~</span>
              <ProFormDigit name={['acInfo', 'powerFactorMax']} noStyle />
            </Space>
          </ProFormText>
        </Col>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.frequencyRange' })}
            {...formItemLayout}
          >
            <Space>
              <ProFormDigit name={['acInfo', 'freqMin']} noStyle />
              <span>~</span>
              <ProFormDigit
                name={['acInfo', 'freqMax']}
                noStyle
                fieldProps={{
                  addonAfter: 'Hz',
                }}
              />
            </Space>
          </ProFormText>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['acInfo', 'overloadCap']}
            label={intl.formatMessage({ id: 'device.overloadCapability' })}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['acInfo', 'curDistRate']}
            label={intl.formatMessage({ id: 'device.currentDistortion' })}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['acInfo', 'acVolHar']}
            label={intl.formatMessage({ id: 'device.acVoltageHarmonic' })}
            fieldProps={{
              prefix: '≤',
              addonAfter: '%',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name={['acInfo', 'dcComponent']}
            label={intl.formatMessage({ id: 'device.dcComponent' })}
            fieldProps={{
              prefix: '≤',
              addonAfter: '%',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['acInfo', 'offGridOutputVol']}
            label={intl.formatMessage({ id: 'device.offGridOutputVoltage' })}
            fieldProps={{
              addonAfter: 'V',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
    </>
  );

  // DC Parameters Form Component
  const DCParametersForm = (
    <>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['dcInfo', 'ratedPower']}
            label={intl.formatMessage({ id: 'device.ratedPower' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzRatedPower' }) },
            ]}
            fieldProps={{
              addonAfter: 'kW',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.cellType' })}
            {...formItemLayout}
            required={true}
          >
            <Space>
              <ProFormDigit
                name={['dcInfo', 'cellVol']}
                noStyle
                rules={[
                  { required: true, message: intl.formatMessage({ id: 'device.PlzCellType' }) },
                ]}
                fieldProps={{
                  addonAfter: 'V',
                }}
              />
              <span>/</span>
              <ProFormDigit
                name={['dcInfo', 'cellCap']}
                rules={[
                  { required: true, message: intl.formatMessage({ id: 'device.PlzCellType' }) },
                ]}
                noStyle
                fieldProps={{
                  addonAfter: 'Ah',
                }}
              />
            </Space>
          </ProFormText>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['dcInfo', 'ratedCap']}
            label={intl.formatMessage({ id: 'device.ratedCapacity' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzRatedCapacity' }) },
            ]}
            fieldProps={{
              addonAfter: 'kWh',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.systemConfiguration' })}
            {...formItemLayout}
            required={true}
          >
            <Space>
              <ProFormDigit
                name={['dcInfo', 'sysP']}
                noStyle
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'device.PlzSystemConfiguration' }),
                  },
                ]}
                fieldProps={{
                  addonAfter: 'P',
                }}
              />
              <span>/</span>
              <ProFormDigit
                name={['dcInfo', 'sysS']}
                noStyle
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'device.PlzSystemConfiguration' }),
                  },
                ]}
                fieldProps={{
                  addonAfter: 'S',
                }}
              />
            </Space>
          </ProFormText>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['dcInfo', 'ratedVol']}
            label={intl.formatMessage({ id: 'device.ratedVoltage' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzRatedVoltage' }) },
            ]}
            fieldProps={{
              addonAfter: 'V',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.dcVoltageRange' })}
            {...formItemLayout}
            required={true}
          >
            <Space>
              <ProFormDigit
                name={['dcInfo', 'volMin']}
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'device.PlzDcVoltageRange' }),
                  },
                ]}
                noStyle
              />
              <span>~</span>
              <ProFormDigit
                name={['dcInfo', 'volMax']}
                noStyle
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'device.PlzDcVoltageRange' }),
                  },
                ]}
                fieldProps={{
                  addonAfter: 'V',
                }}
              />
            </Space>
          </ProFormText>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['dcInfo', 'rate']}
            label={intl.formatMessage({ id: 'device.ratedChargeDischargeRate' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzRatedChargeDischargeRate' }),
              },
            ]}
            placeholder={intl.formatMessage({ id: 'strategyAction.pleaseEnter' })}
            fieldProps={{
              addonAfter: 'C',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
    </>
  );

  // System Parameters Form Component
  const SystemParametersForm = (
    <>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['systemInfo', 'systemEffiMax']}
            label={intl.formatMessage({ id: 'device.maxSystemEfficiency' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzMaxSystemEfficiency' }),
              },
            ]}
            fieldProps={{
              addonAfter: '%',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'systemEffi']}
            label={intl.formatMessage({ id: 'device.operatingEfficiency' })}
            fieldProps={{
              addonAfter: '%',
            }}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzOperatingEfficiency' }),
              },
            ]}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'cycleLife']}
            label={intl.formatMessage({ id: 'device.cycleLife' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzCycleLife' }) }]}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'temp']}
            label={intl.formatMessage({ id: 'device.operatingTemperature' })}
            required={deveiceType === 1}
            rules={[
              {
                required: deveiceType === 1,
                message: intl.formatMessage({ id: 'device.PlzOperatingTemperature' }),
              },
            ]}
            fieldProps={{
              addonAfter: '℃',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'relativeHumidity']}
            label={intl.formatMessage({ id: 'device.relativeHumidity' })}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzRelativeHumidity' }),
              },
            ]}
            fieldProps={{
              addonAfter: '%',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'altitude']}
            label={intl.formatMessage({ id: 'device.altitude' })}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzAltitude' }),
              },
            ]}
            fieldProps={{
              addonAfter: 'km',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'protectLevel']}
            label={intl.formatMessage({ id: 'device.protectionClass' })}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzProtectionClass' }),
              },
            ]}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'coolType']}
            label={intl.formatMessage({ id: 'device.coolingMethod' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzCoolingMethod' }) },
            ]}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'corroLevel']}
            label={intl.formatMessage({ id: 'device.corrosionProtection' })}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzCorrosionProtection' }),
              },
            ]}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'fireSys']}
            label={intl.formatMessage({ id: 'device.fireProtectionSystem' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzFireProtectionSystem' }),
              },
            ]}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'commuType']}
            label={intl.formatMessage({ id: 'device.communicationMethod' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzCommunicationMethod' }),
              },
            ]}
            required={true}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.dimensions' })}
            required={true}
            {...formItemLayout}
          >
            <Space>
              <ProFormDigit
                rules={[{ required: true, message: intl.formatMessage({ id: 'device.height' }) }]}
                name={['systemInfo', 'height']}
                placeholder={intl.formatMessage({ id: 'device.PlzHeight' })}
                noStyle
              />
              <span>*</span>
              <ProFormDigit
                rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzWidth' }) }]}
                name={['systemInfo', 'width']}
                placeholder={intl.formatMessage({ id: 'device.width' })}
                noStyle
              />
              <span>*</span>
              <ProFormDigit
                rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzDepth' }) }]}
                name={['systemInfo', 'depth']}
                placeholder={intl.formatMessage({ id: 'device.depth' })}
                noStyle
              />
              <span>mm</span>
            </Space>
          </ProFormText>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['systemInfo', 'weight']}
            label={intl.formatMessage({ id: 'device.weight' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzWeight' }) }]}
            fieldProps={{
              addonAfter: 'KG',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['systemInfo', 'certStandards']}
            label={intl.formatMessage({ id: 'device.certificationStandards' })}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzCertificationStandards' }),
              },
            ]}
            {...formItemLayout}
          />
        </Col>
      </Row>
    </>
  );

  // Battery Cell Parameters Form Component
  const BatteryCellParametersForm = (
    <>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['batteryCellInfo', 'brand']}
            label={intl.formatMessage({ id: 'device.cellBrand' })}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzCellBrand' }) }]}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormText
            name={['batteryCellInfo', 'cert']}
            label={intl.formatMessage({ id: 'device.cellCertification' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzCellCertification' }),
              },
            ]}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['batteryCellInfo', 'cap']}
            label={intl.formatMessage({ id: 'device.nominalCapacity' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzNominalCapacity' }) },
            ]}
            fieldProps={{
              addonAfter: 'Ah',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name={['batteryCellInfo', 'chargeCur']}
            label={intl.formatMessage({ id: 'device.nominalChargeCurrent' })}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzNominalChargeCurrent' }),
              },
            ]}
            fieldProps={{
              addonAfter: 'A',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['batteryCellInfo', 'chargeCurMax']}
            label={intl.formatMessage({ id: 'device.maxChargeCurrent' })}
            required={true}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzMaxChargeCurrent' }) },
            ]}
            fieldProps={{
              addonAfter: 'A',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name={['batteryCellInfo', 'dischargeCur']}
            label={intl.formatMessage({ id: 'device.nominalDischargeCurrent' })}
            required={true}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzNominalDischargeCurrent' }),
              },
            ]}
            fieldProps={{
              addonAfter: 'A',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormDigit
            name={['batteryCellInfo', 'dischargeCurMax']}
            label={intl.formatMessage({ id: 'device.maxDischargeCurrent' })}
            rules={[
              {
                required: true,
                message: intl.formatMessage({ id: 'device.PlzMaxDischargeCurrent' }),
              },
            ]}
            fieldProps={{
              addonAfter: 'A',
            }}
            {...formItemLayout}
          />
        </Col>
        <Col span={12}>
          <ProFormDigit
            name={['batteryCellInfo', 'energyEffi']}
            label={intl.formatMessage({ id: 'device.energyEfficiency' })}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'device.PlzEnergyEfficiency' }) },
            ]}
            fieldProps={{
              addonAfter: '%',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.dimensions' })}
            required={true}
            {...formItemLayout}
          >
            <Space>
              <ProFormDigit
                rules={[{ required: true, message: intl.formatMessage({ id: 'device.length' }) }]}
                name={['batteryCellInfo', 'length']}
                placeholder={intl.formatMessage({ id: 'device.PlzLength' })}
                noStyle
              />{' '}
              <span>*</span>
              <ProFormDigit
                rules={[
                  { required: true, message: intl.formatMessage({ id: 'device.PlzHeight' }) },
                ]}
                name={['batteryCellInfo', 'height']}
                placeholder={intl.formatMessage({ id: 'device.PlzHeight' })}
                noStyle
              />
              <span>*</span>
              <ProFormDigit
                rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzWidth' }) }]}
                name={['batteryCellInfo', 'width']}
                placeholder={intl.formatMessage({ id: 'device.width' })}
                noStyle
              />
              <span>mm</span>
            </Space>
          </ProFormText>
        </Col>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.storageTemperatureRange' })}
            required={true}
            {...formItemLayout}
          >
            <Space>
              <ProFormDigit
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'device.PlzStorageTemperatureRange' }),
                  },
                ]}
                name={['batteryCellInfo', 'storageTmpMin']}
                noStyle
              />
              <span>~</span>
              <ProFormDigit
                rules={[
                  {
                    required: true,
                    message: intl.formatMessage({ id: 'device.PlzStorageTemperatureRange' }),
                  },
                ]}
                name={['batteryCellInfo', 'storageTmpMax']}
                noStyle
                fieldProps={{
                  addonAfter: '℃',
                }}
              />
            </Space>
          </ProFormText>
        </Col>
      </Row>
      <Row gutter={24}>
        <Col span={12}>
          <ProFormText
            label={intl.formatMessage({ id: 'device.operatingTemperatureRange' })}
            required={deveiceType === 1}
            {...formItemLayout}
          >
            <div style={{ width: '540px' }}>
              <div style={{ marginBottom: 16 }}>
                <Space>
                  <span
                    style={{
                      marginRight: 8,
                      textWrap: 'nowrap',
                    }}
                  >
                    {intl.formatMessage({ id: 'device.chargingStatus' })}:
                  </span>
                  <ProFormDigit
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({ id: 'device.PlzChargingStatus' }),
                      },
                    ]}
                    name={['batteryCellInfo', 'chargeTmpMin']}
                    noStyle
                    fieldProps={{
                      addonAfter: '℃',
                    }}
                  />
                  <span>~</span>
                  <ProFormDigit
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({ id: 'device.PlzChargingStatus' }),
                      },
                    ]}
                    name={['batteryCellInfo', 'chargeTmpMax']}
                    noStyle
                    fieldProps={{
                      addonAfter: '℃',
                    }}
                  />
                </Space>
              </div>
              <div>
                <Space>
                  <span
                    style={{
                      marginRight: 8,
                      textWrap: 'nowrap',
                    }}
                  >
                    {intl.formatMessage({ id: 'device.dischargingStatus' })}:
                  </span>
                  <ProFormDigit
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({ id: 'device.PlzDischargingStatus' }),
                      },
                    ]}
                    name={['batteryCellInfo', 'dischargeTmpMin']}
                    noStyle
                    fieldProps={{
                      addonAfter: '℃',
                    }}
                  />
                  <span>~</span>
                  <ProFormDigit
                    rules={[
                      {
                        required: true,
                        message: intl.formatMessage({ id: 'device.PlzDischargingStatus' }),
                      },
                    ]}
                    name={['batteryCellInfo', 'dischargeTmpMax']}
                    noStyle
                    fieldProps={{
                      addonAfter: '℃',
                    }}
                  />
                </Space>
              </div>
            </div>
          </ProFormText>
        </Col>
      </Row>
      <Row gutter={16}>
        <Col span={12}>
          <ProFormText
            name={['batteryCellInfo', 'humidity']}
            label={intl.formatMessage({ id: 'device.humidity' })}
            required={true}
            rules={[{ required: true, message: intl.formatMessage({ id: 'device.PlzHumidity' }) }]}
            fieldProps={{
              addonAfter: '%',
            }}
            {...formItemLayout}
          />
        </Col>
      </Row>
    </>
  );
  const items: TabsProps['items'] = [
    {
      key: '1',
      label: intl.formatMessage({ id: 'device.basicInfo' }),
      forceRender: true,
    },
    deveiceType === 1 && {
      key: '2',
      label: intl.formatMessage({ id: 'device.acParameters' }),
      forceRender: true,
    },
    {
      key: '3',
      label: intl.formatMessage({ id: 'device.dcParameters' }),
      forceRender: true,
    },
    {
      key: '4',
      label: intl.formatMessage({ id: 'device.systemParameters' }),
      forceRender: true,
    },
    {
      key: '5',
      label: intl.formatMessage({ id: 'device.cellParameters' }),
      forceRender: true,
    },
  ];
  const renderAllTabs = () => {
    return (
      <div>
        {/* 基础信息 */}
        <div style={{ display: activeTab === '1' ? 'block' : 'none' }}>{BasicInfoForm}</div>

        {/* 交流侧参数 */}
        {deveiceType === 1 && (
          <div style={{ display: activeTab === '2' ? 'block' : 'none' }}>{ACParametersForm}</div>
        )}
        {/* 直流侧参数 */}
        <div style={{ display: activeTab === '3' ? 'block' : 'none' }}>{DCParametersForm}</div>

        {/* 系统参数 */}
        <div style={{ display: activeTab === '4' ? 'block' : 'none' }}>{SystemParametersForm}</div>
        {/*  电芯参数*/}
        <div style={{ display: activeTab === '5' ? 'block' : 'none' }}>
          {BatteryCellParametersForm}
        </div>
      </div>
    );
  };
  // 3. 在表单验证失败时，找到第一个有错误的 tab 并激活
  const handleFormError = (errorFields: any[]) => {
    // 定义每个 tab 对应的字段前缀
    const tabFieldMapping = {
      '1': [
        'deviceModel',
        'manufacturer',
        'pcsType',
        'status',
        'pictureDir',
        'listingDay',
        'remark',
      ],
      '2': ['acInfo'],
      '3': ['dcInfo'],
      '4': ['systemInfo'],
      '5': ['batteryCellInfo'],
    };

    // 查找第一个包含错误的 tab
    for (const [tabKey, fieldPrefixes] of Object.entries(tabFieldMapping)) {
      const hasError = errorFields.some((error) =>
        fieldPrefixes.some((prefix) => error.name[0].startsWith(prefix)),
      );

      if (hasError) {
        setActiveTab(tabKey);
        break;
      }
    }
  };
  return (
    <div>
      <ProTable<API.DeviceBasicDocVO, API.PageParams>
        actionRef={actionRef}
        formRef={formRef}
        rowKey="id"
        params={{ stationId, deviceType: deveiceType }}
        request={getList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        toolBarRender={() => []}
        customToolBarClass="global-tabs-custom-tools"
      />
      <ModalForm
        className={Styles.modalTitle}
        modalProps={{
          destroyOnClose: true,
          width: intl.locale === 'en-US' ? 1200 : 800,
        }}
        initialValues={{
          status: true,
          ...currentRow,
          type: currentRow?.type?.toString() ?? '1',
        }}
        submitter={{
          render: (_, doms) => !readonly && <Space>{doms}</Space>,
        }}
        title={
          currentRow?.id
            ? `${
                readonly
                  ? intl.formatMessage({ id: 'systemManagement.generalProcedure.view' })
                  : intl.formatMessage({ id: 'systemManagement.generalProcedure.edit' })
              } ${titleName}`
            : `${intl.formatMessage({
                id: 'systemManagement.generalProcedure.new',
              })} ${titleName}`
        }
        // readonly={currentRow?.id && readonly}
        disabled={currentRow?.id && readonly}
        layout="horizontal"
        width={intl.locale === 'en-US' && deveiceType === 1 ? 1200 : 800}
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          let success;
          value.pictureDir = imgUrl;
          value.stationId = stationId;
          value.deviceType = deveiceType;
          if (currentRow?.id) {
            success = await handleEdit({ ...currentRow, ...value } as API.DeviceBasicDocVO);
          } else {
            success = await handleAdd(value as API.DeviceBasicDocVO);
          }
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onFinishFailed={({ errorFields }) => {
          handleFormError(errorFields);
        }}
      >
        <Tabs items={items} activeKey={activeTab} onChange={setActiveTab} />
        {renderAllTabs()}
      </ModalForm>
      {imgUrl && (
        <Image
          wrapperStyle={{ display: 'none' }}
          preview={{
            visible: previewOpen,
            onVisibleChange: (visible) => setPreviewOpen(visible),
          }}
          src={imgUrl}
        />
      )}
    </div>
  );
});

export default Table;
